package cn.tannn.tgateway;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.DispatcherHandler;
import org.springframework.web.reactive.handler.SimpleUrlHandlerMapping;

import java.util.Properties;

import static cn.tannn.tgateway.GatewayPlugin.GATEWAY_PREFIX;

/**
 * gateway config
 * @author <a href="https://t.tannn.cn/">tan</a>
 * @date 2024/5/30 上午10:33
 * @see DispatcherHandler#initStrategies(ApplicationContext)
 * @see SimpleUrlHandlerMapping#setMappings(Properties)
 */
@Configuration
@Slf4j
public class GatewayConfig {


    /**
     * 注册 RouterFunction
     * <P> 不构建一个新的mapping，而是复用HandlerAdapter的SimpleUrlHandlerMapping实现，往里面加一个自己的handler
     * @param context ApplicationContext
     * @return ApplicationRunner
     */
    @Bean
    ApplicationRunner runner(@Autowired ApplicationContext context) {
        return args -> {
            SimpleUrlHandlerMapping handlerMapping = context.getBean(SimpleUrlHandlerMapping.class);
            Properties mappings = new Properties();
            mappings.put(GATEWAY_PREFIX + "/**", "gatewayWebHandler");
            // 追加自己的 Handler
            handlerMapping.setMappings(mappings);
            // 刷新一下
            handlerMapping.initApplicationContext();
            log.debug("tan gateway start");
        };
    }
}
